package com.imooc.sellspringcloud.server.mq;

import com.imooc.sellspringcloud.server.dto.OrderDTO;
import com.imooc.sellspringcloud.server.redis.RedisService;
import com.imooc.sellspringcloud.server.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

/**
 * @author
 * @create 2019-08-07 21:50
 **/
@Service
@Slf4j
public class ProductReceive {

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    OrderService orderService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "create-order-queue", durable = "false"),
            exchange = @Exchange(value = "create-order-exchange",
                    durable = "false", type = "topic"),
            key = "createOrderKey"
    ))
    @RabbitHandler
    public void receive(Message message, Channel channel) {
        String payload = (String) message.getPayload();
        log.info("message info {}", payload);
        try {

            OrderDTO orderDTO = (OrderDTO) RedisService.stringToBean(payload, OrderDTO.class);

            orderService.create(orderDTO);

            Long dec = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);

            channel.basicAck(dec, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}